import React from 'react';
import { fetchProcess, fetchDetail } from '@/services/flowMine/waitApprovals';
import { message } from 'antd';
import { fetchDetailFromNewFlow, fetchProcessFromNewFlow } from '../service';

const useProcessDetail = (query = {}) => {
    const [data, setData] = React.useState({ detail: {}, step: [] });
    const [loading, setLoading] = React.useState(true);
    const [hasError, setHasError] = React.useState(false);
    const [isNewWorkFlow, setIsNewWorkFlow] = React.useState(null);

    React.useEffect(() => {
        const checkWorkFlowVersion = applicationNo => applicationNo.includes('-');

        const fetch = async () => {
            setLoading(true);
            setHasError(false);

            // 检查当前的applicationNo 是否包含 - 包含则为新版本，否则为旧版本
            const isNewVersion = checkWorkFlowVersion(query.applicationNo);

            setIsNewWorkFlow(!!isNewVersion);
            Promise.all(
                isNewVersion
                    // eslint-disable-next-line max-len
                    ? [fetchProcessFromNewFlow({ applicationNo: query.applicationNo }), fetchDetailFromNewFlow({ applicationNo: query.applicationNo })]
                    : [fetchProcess(query.applicationNo), fetchDetail(query)]
            )
                .then(_data => {
                    const [stepResult, detailResult] = _data;
                    // 无权限
                    if ([stepResult.code, detailResult.code].includes(30021)) {
                        message.error(stepResult.msg);
                        setHasError(true);
                        return;
                    }
                    if (stepResult.code === 10000 && detailResult.code === 10000) {
                        setData({ ...data, step: stepResult.data, detail: detailResult.data });
                    }
                })
                .finally(() => {
                    setLoading(false);
                });
        };

        if (query?.applicationNo) {
            fetch();
        }
    }, [query]);

    return [loading, data, hasError, isNewWorkFlow];
};

export default useProcessDetail;
